package com.itcast.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itcast.constant.MessageConstant;
import com.itcast.dto.InsertMemberDTO;
import com.itcast.entity.PageResult;
import com.itcast.entity.QueryPageBean;
import com.itcast.entity.Result;
import com.itcast.pojo.Member;
import com.itcast.pojo.User;
import com.itcast.service.MemberService;
import com.itcast.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @className: UserController
 * @description: TODO 类描述
 * @author: Jng
 * @date: 2022/4/18
 **/
@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    UserService userService;
    @Reference
    MemberService memberService;
    //获取当前登录用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername()throws Exception{
        try{
            org.springframework.security.core.userdetails.User user =
                    (org.springframework.security.core.userdetails.User)
                            SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,user.getUsername());
        }catch (Exception e){
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }

    @RequestMapping("/registerUser")
    public Result registerUser(@RequestBody User user){
        return userService.registerUser(user);
    }

    /**
     * 展示会员列表
     * @param queryPageBean
     * @return
     */
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return userService.findPage(queryPageBean);
    }

    @RequestMapping("/delete")
    public Result deleteUserById(@RequestParam("id") Integer id)
    {
        if(userService.deleteById(id)){

            return new Result(true,MessageConstant.DELETE_USER_SUCCESS);
        }
        return new Result(false,MessageConstant.DELETE_USER_FAIL);
    }

    @RequestMapping("/add")
    public Result addUser(@RequestBody InsertMemberDTO insertMemberDTO){
        return memberService.addUser(insertMemberDTO);
    }
}
